package ai.yue.open.service.cd.service;

import ai.yue.library.base.view.R;
import ai.yue.library.base.view.Result;
import ai.yue.library.web.util.ServletUtils;
import ai.yue.open.service.cd.entity.Workload;
import ai.yue.open.service.cd.entity.WorkloadRedeployLog;
import ai.yue.open.service.cd.mapper.WorkloadRedeployLogMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 工作负载重新部署日志
 *
 * @author yl-yue
 * @since  2023/2/7
 */
@Service
@RequiredArgsConstructor
public class WorkloadRedeployLogService extends ServiceImpl<WorkloadRedeployLogMapper, WorkloadRedeployLog> {

    final WorkloadService workloadService;

    public Result<?> deleteById(Long id) {
        return R.success(removeById(id));
    }

    public Result<?> deleteByIds(List<Long> ids) {
        return R.success(removeByIds(ids));
    }

    public Result<?> page() {
        PageHelper.startPage(ServletUtils.getRequest());
        List<WorkloadRedeployLog> list = list();
        if (list.isEmpty()) {
            return R.success(PageInfo.of(list));
        }

        List<Long> workloadIdList = list.stream().map(workloadRedeployLog -> workloadRedeployLog.getWorkloadId()).collect(Collectors.toList());
        workloadService.lambdaQuery()
                .in(Workload::getId, workloadIdList)
                .list()
                .forEach(workload -> list.stream()
                        .filter(workloadRedeployLog -> workloadRedeployLog.getWorkloadId().equals(workload.getId()))
                        .forEach(workloadRedeployLog -> {
                            workloadRedeployLog.setNamespace(workload.getNamespace());
                            workloadRedeployLog.setWorkloadName(workload.getWorkloadName());
                        })
                );

        return R.success(PageInfo.of(list));
    }

}
